package com.aiti.lulian.service.newCard;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.aiti.base.core.base.service.iml.BaseSerivceImpl;
import com.aiti.base.core.exception.BusinessException;
import com.aiti.lulian.dto.newCard.EnterpriseCardQRParamDto;
import com.aiti.lulian.entity.newCard.CardEnterpriseQr;
import com.aiti.lulian.mapper.newCard.CardEnterpriseQrMapper;
import com.aiti.lulian.utils.BusinessUtil;
import com.aiti.lulian.vo.newCard.EnterpriseCardQRVo;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.Date;

/**
 * description:
 * auth fcb
 * date 2025-09-05 11:49
 **/
@Service
@Slf4j
public class CardEnterpriseQrService extends BaseSerivceImpl<CardEnterpriseQrMapper, CardEnterpriseQr> {


    /**
     * 生成邀请员工二维码
     * @param paramDto
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public EnterpriseCardQRVo generateQR(EnterpriseCardQRParamDto paramDto) {
        this.checkParam(paramDto);
        Integer qrType = null;
        String auditBaseId = paramDto.getAuditBaseId();
        if(StrUtil.isBlank(paramDto.getAuditBaseId())) {
            qrType = 1;
            auditBaseId = "no";
        }else {
            qrType = 2;
        }
        // 查询该模板的二维码是否已经存在
        EnterpriseCardQRVo enterpriseCardQRVo = this.baseMapper.queryEnterpriseQR(paramDto.getEnterpriseId(), paramDto.getTemplateId(), qrType, auditBaseId);
        if(enterpriseCardQRVo != null) {
            return enterpriseCardQRVo;
        }
        CardEnterpriseQr qr = new CardEnterpriseQr();
        String baseId = IdUtil.simpleUUID();
        qr.setBaseId(baseId);
        qr.setEnterpriseId(paramDto.getEnterpriseId());
        qr.setTemplateId(paramDto.getTemplateId());
        qr.setQrCode(this.generateQRCode(paramDto));
        qr.setQrType(qrType);
        qr.setAuditBaseId(auditBaseId);
        // 默认永久有效
        qr.setExpireTimeType(1);
        if(paramDto.getExpireTimeType() != null && paramDto.getExpireTimeType() == 2) {
            qr.setExpireTime(DateUtil.parse(paramDto.getExpireTime()));
        }
        qr.setBaseCreateBy(paramDto.getUserId());
        qr.setBaseCreateTime(new Date());
        qr.setBaseUpdateBy(paramDto.getUserId());
        qr.setBaseUpdateTime(new Date());
        this.save(qr);
        EnterpriseCardQRVo vo = new EnterpriseCardQRVo();
        vo.setBaseId(baseId);
        vo.setQrCode(qr.getQrCode());
        vo.setExpireTimeType(1);
        return vo;
    }

    /**
     * 更新二维码有效期
     * @param paramDto
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public EnterpriseCardQRVo updateQRExpireTime(EnterpriseCardQRParamDto paramDto) {
        if(StrUtil.isBlank(paramDto.getBaseId())) {
            throw new BusinessException("参数错误");
        }
        if(paramDto.getExpireTimeType() == null) {
            throw new BusinessException("参数错误");
        }
        EnterpriseCardQRVo vo = new EnterpriseCardQRVo();
        vo.setBaseId(paramDto.getBaseId());
        if(paramDto.getExpireTimeType() == 1) {
            vo.setExpireTimeType(1);
            this.baseMapper.updateQRExpireTime(paramDto.getBaseId(), paramDto.getExpireTimeType(), null, paramDto.getUserId());
        } else {
            DateTime dateTime = DateUtil.offsetDay(new Date(), 7);
            String expireTime = dateTime.toString("yyyy-MM-dd HH:mm");
            this.baseMapper.updateQRExpireTime(paramDto.getBaseId(), paramDto.getExpireTimeType(), expireTime, paramDto.getUserId());
            vo.setExpireTime(expireTime);
            vo.setExpireTimeType(2);
        }
        return vo;
    }

    private String generateQRCode(EnterpriseCardQRParamDto paramDto){
        String auditBaseId = paramDto.getAuditBaseId();
        if(StrUtil.isBlank(auditBaseId)) {
            auditBaseId = "no";
        }
        String baerUrl = paramDto.getBaseUrl();
        if(StrUtil.isBlank(baerUrl)) {
            baerUrl = "https://yunzhanting.org.cn/invitation";
        }
        // userId是生成这个二维码的用户id，一般都是企业管理员
        String content = baerUrl + "?enterpriseId=" + paramDto.getEnterpriseId() + "&templateId=" + paramDto.getTemplateId() + "&userId=" + paramDto.getUserId() + "&auditBaseId=" + auditBaseId;
        QrConfig qrConfig = new QrConfig();
        qrConfig.setHeight(paramDto.getHeight());
        qrConfig.setWidth(paramDto.getWidth());
        qrConfig.setErrorCorrection(ErrorCorrectionLevel.H);
        BufferedImage logoImage = null;
        try {
            logoImage = ImageIO.read(new ClassPathResource("qrlogo.png").getStream());
            qrConfig.setImg(logoImage);
        }catch (IOException e) {
            log.error("读取二维码logo图片异常：{}", ExceptionUtil.stacktraceToString(e));
        }
        //qrConfig.setImg("classpath:qrlogo.png");
        BufferedImage bufferedImage = QrCodeUtil.generate(content, qrConfig);
        return BusinessUtil.bufferedImageToBase64(bufferedImage, "png");
    }



    private void checkParam(EnterpriseCardQRParamDto paramDto) {
        if(StrUtil.isBlank(paramDto.getEnterpriseId())) {
            throw new BusinessException("企业id不能为空");
        }
        if(StrUtil.isBlank(paramDto.getTemplateId())) {
            throw new BusinessException("模板不能为空");
        }
        if(StrUtil.isBlank(paramDto.getUserId())) {
            throw new BusinessException("用户id不能为空");
        }
    }

}
